import Dexie from 'dexie'

const dbName = 'message-log'

const db = new Dexie(dbName)
const dbVersion = 1

let isDbInitialized = false

const initDb = () => {
  if (isDbInitialized) {
    return Promise.resolve()
  }

  try {
    db.version(dbVersion).stores({
      //                 来源    自定义名称    通话时长             手机号  时间          模式 点呼1  群呼2
      logMessage: '++id, source,sourceName,duration, tenantId, number,timer,callId,model',
      //               时间      内容           ai还是手动还是别的
      aiMessage: '++id,timer,content,uuid,type'
    })

    isDbInitialized = true
    return db.open()
  } catch (error) {
    console.error('数据库初始化失败:', error)
    return Promise.reject(error)
  }
}

const close = () => {
  db.close()
  isDbInitialized = false
}

// 查询
const searchLogMessage = async ({ pageNo = 1, pageSize = 10, tenantId, number } = {}) => {
  try {
    const offset = (pageNo - 1) * pageSize
    let collection = db.logMessage.orderBy('id').and((task) => task.tenantId == tenantId)

    // 如果传入了number参数，添加模糊搜索条件
    if (number) {
      collection = collection.filter(
        (task) => task.number && task.number.toString().includes(number.toString())
      )
    }

    const total = await collection.count()
    const list = await collection.reverse().offset(offset).limit(pageSize).toArray()

    return {
      list: list || [],
      total
    }
  } catch (error) {
    console.error('分页查询日志失败:', error)
    return {
      list: [],
      total: 0
    }
  }
}

// 删除全部
const delLogMessageAll = async (tenantId) => {
  try {
    const arr = await db.logMessage
      .orderBy('id')
      .and((task) => task.tenantId == tenantId)
      .toArray()
    const arrId = arr.map((item) => item.id) || []
    return await db.logMessage.bulkDelete(arrId)
  } catch (error) {
    console.error('清空失败:', error)
    throw error
  }
}

// 添加
const addLogMessage = async (obj) => {
  return db.logMessage.add(obj)
}

// 删除单条
const delLogMessage = async (id) => {
  return db.logMessage.delete(id)
}

// 修改时长
const updateLogMessage = async (id, value) => {
  return db.logMessage.update(id, { duration: value })
}

// 根据callid查找
const findLogMessage = async (callId) => {
  return await db.logMessage.where('callId').equals(callId).first()
}

// 对话添加
const addAiMessage = async (obj) => {
  try {
    await initDb()
    return db.aiMessage.add(obj)
  } catch (error) {
    console.error('添加对话失败:', error)
    throw error
  }
}

// 修改对话
const updateAiMessage = async (uuid, content) => {
  try {
    await initDb()
    return db.aiMessage.where('uuid').equals(uuid).modify({
      content: content,
      timer: new Date().getTime() // 更新时间戳
    })
  } catch (error) {
    console.error('修改对话失败:', error)
    throw error
  }
}

// 删除对话
const delAiMessage = async (uuid) => {
  try {
    await initDb()
    return db.aiMessage.where('uuid').equals(uuid).delete()
  } catch (error) {
    console.error('删除对话失败:', error)
    throw error
  }
}

// 修复：根据type查询对话列表，按时间倒序
const getAiMessagesByType = async (type) => {
  try {
    await initDb()
    // 先获取所有按时间排序的记录，然后过滤
    const allMessages = await db.aiMessage.orderBy('timer').reverse().toArray()
    return allMessages.filter((msg) => msg.type === type)
  } catch (error) {
    console.error('根据type查询对话失败:', error)
    return []
  }
}

// 修复：根据uuid查询对话内容
const getAiMessageByUuid = async (uuid) => {
  try {
    await initDb()
    return await db.aiMessage.where('uuid').equals(uuid).first()
  } catch (error) {
    console.error('根据uuid查询对话失败:', error)
    return null
  }
}

export {
  initDb,
  searchLogMessage,
  delLogMessage,
  addLogMessage,
  delLogMessageAll,
  updateLogMessage,
  findLogMessage,
  addAiMessage,
  updateAiMessage,
  delAiMessage,
  getAiMessagesByType,
  getAiMessageByUuid,
  close
}
